import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useWallpaperStore = defineStore('wallpaper', () => {
  // 当前壁纸
  const currentWallpaper = ref<string>('/wallpapers/1300373.jpg')

  // 可用壁纸列表
  const availableWallpapers = ref<string[]>([
    '/wallpapers/1300373.jpg',
    '/wallpapers/1301397.jpg',
    '/wallpapers/1302305.jpg',
    '/wallpapers/1302785.jpg',
    '/wallpapers/1304142.jpg',
    '/wallpapers/1305045.jpg',
  ])

  // 设置壁纸
  const setWallpaper = (wallpaper: string) => {
    currentWallpaper.value = wallpaper
    // 保存到本地存储，以便刷新后仍能保持
    localStorage.setItem('wallpaper', wallpaper)
  }

  // 添加壁纸到列表
  const addWallpaper = (wallpaper: string) => {
    if (!availableWallpapers.value.includes(wallpaper)) {
      availableWallpapers.value.push(wallpaper)
      // 保存到本地存储
      localStorage.setItem('wallpapers', JSON.stringify(availableWallpapers.value))
    }
  }

  // 从列表中移除壁纸
  const removeWallpaper = (wallpaper: string) => {
    const index = availableWallpapers.value.indexOf(wallpaper)
    if (index !== -1) {
      availableWallpapers.value.splice(index, 1)
      // 保存到本地存储
      localStorage.setItem('wallpapers', JSON.stringify(availableWallpapers.value))
      
      // 如果当前壁纸被移除，切换到默认壁纸
      if (currentWallpaper.value === wallpaper) {
        currentWallpaper.value = availableWallpapers.value[0] || '/wallpapers/1300373.jpg'
        localStorage.setItem('wallpaper', currentWallpaper.value)
      }
    }
  }

  // 初始化，从本地存储加载设置
  const init = () => {
    // 加载壁纸设置
    const savedWallpaper = localStorage.getItem('wallpaper')
    if (savedWallpaper) {
      currentWallpaper.value = savedWallpaper
    }

    // 加载壁纸列表
    const savedWallpapers = localStorage.getItem('wallpapers')
    if (savedWallpapers) {
      try {
        const parsedWallpapers = JSON.parse(savedWallpapers)
        if (Array.isArray(parsedWallpapers)) {
          availableWallpapers.value = parsedWallpapers
        }
      } catch (error) {
        console.error('Error parsing wallpapers from localStorage:', error)
      }
    }
  }

  // 初始化
  init()

  return {
    currentWallpaper,
    availableWallpapers,
    setWallpaper,
    addWallpaper,
    removeWallpaper
  }
}) 